const { convert } = require("../utils/transform_tool");
const { BaseCommand } = require("./base");

class TruncateAllCommand extends BaseCommand {
    async execute() {
        const data = this.selfData;
        const content = this.content;
        let flags = data.flags || "";
        if (flags.indexOf("g") === -1) {
            flags += "g";
        }
        const struct = data.struct;
        const reg = new RegExp(data.pattern, flags);
        const matches = [];
        let match;
        const full_match = data.full_match;
        while ((match = reg.exec(content))) {
            let obj;
            if (Array.isArray(struct)) {
                obj = {};
                // 匹配的完整字符串由 $ 表示
                if (struct[0] !== "$") {
                    struct.unshift("$");
                }
                match.forEach((v, i) => {
                    if (!full_match && i === 0) {
                        return;
                    }
                    const prop = struct[i];
                    let name;
                    let value = data.trim ? v.trim() : v;
                    if (typeof prop === "object") {
                        name = prop.name;
                        value = convert(value, prop.type);
                    } else {
                        name = prop;
                    }

                    obj[name] = value;
                });
            } else {
                obj = full_match ? match : match.slice(1);
            }
            matches.push(obj);
        }
        return matches;
    }

    getRequireContent() {
        return true;
    }

    getRequiredParams() {
        return ["pattern"];
    }
}

module.exports = {
    TruncateAllCommand,
};
